package com.zhu.storesmanager;

import java.util.ArrayList;
import java.util.List;

import com.zhu.storesmanager.models.BrandsDataItem;
import com.zhu.storesmanager.models.ProjectDataItem;
import com.zhu.storesmanager.models.SpecialTaskItem;
import com.zhu.storesmanager.models.SyncModel;
import com.zhu.storesmanager.models.UserData;
import com.zhu.storesmanager.models.VisitTaskInfo;
import com.zhu.storesmanager.provider.StoresManagerSettings;
import com.zhu.storesmanager.utils.Actions;
import com.zhu.storesmanager.utils.DataUtils;
import com.zhu.storesmanager.utils.DatabaseUtil;
import com.zhu.storesmanager.utils.Log;
import com.zhu.storesmanager.utils.ViewsUtil;
import com.zhu.storesmanager.views.PopEditText;
import com.zhu.storesmanager.views.PopMenu;
import com.zhu.storesmanager.views.PopTextView;

import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 特殊任务处理
 */
public class SpecialTaskActivity extends Activity implements View.OnClickListener{

	//异步查询数据库token
	private final static int TASK_LIST_QUERY_TOKEN = 0; //查询所有任务 token 
	private final static int TASKDATA_LIST_QUERY_TOKEN = 1; //查询所有任务反馈数据 token 
	private DataQueryHandler mDataQueryHandler = null; //数据异步查询Handler
	private List<SpecialTaskItem> mSpecialTaskList = new ArrayList<SpecialTaskItem>(); //任务集合
	private FrameLayout mFrameLayout = null; //界面布局
	private PopTextView mPopTextView = null; //任务描述弹窗
	private PopEditText mPopEditText = null; //任务反馈输入框

	private TextView mTitleView = null; //标题栏
	private LinearLayout mBodyView = null; //所有任务列表内容界面
	private VisitTaskInfo mVisitTaskInfo = null; //拜访门店数
	private PopMenu mPopMenu = null; //弹出菜单
	private boolean isDataChange = true; //数据是否发生

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Parcelable parcelable = getIntent().getParcelableExtra("info");
        mVisitTaskInfo = (VisitTaskInfo) parcelable;
		setContentView(R.layout.activity_specialtask); //设置显示界面布局
		setupViews();
		initData();
	}

	/**
	 * 初始化界面
	 */
	private void setupViews(){
		mTitleView = (TextView)findViewById(R.id.title_text);
		mBodyView = (LinearLayout)findViewById(R.id.list_body);
		mFrameLayout = (FrameLayout)findViewById(R.id.layout_content);

		findViewById(R.id.svbottom_menu_back).setOnClickListener(this);
        findViewById(R.id.svbottom_menu_save).setOnClickListener(this);
        if(DataUtils.mUserData.mRoleType == UserData.USERTYPE_SUPERVISOR){
        	findViewById(R.id.svbottom_menu_menu).setOnClickListener(this);
        	mPopMenu = new PopMenu(this, findViewById(R.id.bottom_menu), PopMenu.MENU_TASK);
            mPopMenu.setVisitTaskInfo(mVisitTaskInfo);
        }else{
        	findViewById(R.id.svbottom_menu_menu).setVisibility(View.GONE);
        	findViewById(R.id.svbottom_split_menu).setVisibility(View.GONE);
        }
		mPopTextView = new PopTextView(mFrameLayout);
		mPopEditText = new PopEditText(mFrameLayout);
	}

	/**
	 * 初始化数据
	 */
	private void initData(){
		mTitleView.setText(R.string.special_task);
		if(!DataUtils.mUserData.isAdmin()){
			mDataQueryHandler = new DataQueryHandler(getContentResolver());
			startQueryTasksList();
		}else{
			setDataFromAdminSearchData();
		}
	}

	/**
	 * 开始查询任务列表
	 */
	private void startQueryTasksList(){
		int typeid = -1;
		if(DataUtils.mUserData.mRoleType == UserData.USERTYPE_SALESPERSON){ //促销员
			typeid = StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_SALERTASK;
		}else if(DataUtils.mUserData.mRoleType == UserData.USERTYPE_SUPERVISOR){ //督导
			typeid = StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_SVTASK;
		}
		String where = StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE +"=" + typeid;
		mDataQueryHandler.startQuery(TASK_LIST_QUERY_TOKEN, null, 
				StoresManagerSettings.DataProjectsColumns.CONTENT_URI_NO_NOTIFICATION,
				null, where, null, null);
	}

	/**
	 * 开始查询任务数据列表
	 */
	private void startQueryTasksDataList(){
		String where = null;
		if(mVisitTaskInfo != null){
			where = StoresManagerSettings.SpecialTaskColumns.STOREID + "=\'" + mVisitTaskInfo.mStoreId +"\'";
		}
		mDataQueryHandler.startQuery(TASKDATA_LIST_QUERY_TOKEN, null, 
				StoresManagerSettings.SpecialTaskColumns.CONTENT_URI_NO_NOTIFICATION,
				null, where, null, null);
	}

	/**
	 * 更具查询结果更新任务数据
	 * @param cursor 查询结果数据
	 */
	private void updateTaskFeedbackListFromCursor(Cursor cursor){
		try {
			//数据索引
			final int dbidIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SpecialTaskColumns._ID);
            final int taskidIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SpecialTaskColumns.TASK_ID);
            final int taskfdIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SpecialTaskColumns.TASK_FEEDBACK);
            while (cursor.moveToNext()) {
            	boolean isSaved = cursor.getInt(cursor.getColumnIndexOrThrow(
        				StoresManagerSettings.SAVED)) == 1 ? true : false;
            	int taskId = cursor.getInt(taskidIndex);
            	SpecialTaskItem item = getSpecialTaskItem(taskId);
            	if(item != null){
            		item.mDbid = cursor.getLong(dbidIndex);
            		if(isSaved){
            			if(item.isSave && item.isShow){
            				item.mTaskFeedback = cursor.getString(taskfdIndex);
            			}else{
            				
            			}
            		}else{
            			item.mTaskFeedback = cursor.getString(taskfdIndex);
            		}
            	}
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("updateTaskListFromCursor error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        		cursor = null;
        	}
        }
		updateBodyList();
	}

	/**
	 * 更新任务列表界面
	 */
	private void updateBodyList(){
		for(int i = 0; i < mSpecialTaskList.size(); i++){
			View view = getView(mSpecialTaskList.get(i));
			mBodyView.addView(view);
		}
	}

	/**
     * 获取任务列表项界面
     * @param item 型号数据
     */
    private View getView(SpecialTaskItem item) {
        View view = LayoutInflater.from(this).inflate(R.layout.specialtask_item, null);
        TextView des = (TextView)view.findViewById(R.id.specialtask_item_name); //任务描述
        des.setTag(item);
        des.setText(item.mTaskDes);
        des.setOnClickListener(this);
        TextView fb = (TextView)view.findViewById(R.id.specialtask_item_text); //任务反馈
        fb.setTag(item);
        fb.setText(item.mTaskFeedback);
        fb.setOnClickListener(this);
        return view;
    }

	/**
	 * 异步数据查询
	 */
	private final class DataQueryHandler extends AsyncQueryHandler {
        public DataQueryHandler(ContentResolver contentResolver) {
            super(contentResolver);
        }

        /**
         * 查询结果返回
         * (non-Javadoc)
         * @see android.content.AsyncQueryHandler#onQueryComplete(int, java.lang.Object, android.database.Cursor)
         */
        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            switch (token) {
                case TASK_LIST_QUERY_TOKEN:
                	updateTaskListFromCursor(cursor);
                    break;
                case TASKDATA_LIST_QUERY_TOKEN:
                    updateTaskFeedbackListFromCursor(cursor);
                    break;
                default:
                    Log.e("onQueryComplete called with unknown token " + token);
            }
        }

        @Override
        protected void onDeleteComplete(int token, Object cookie, int result) {

        }
    }

	/**
	 * (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if(arg0 != null){
			switch(arg0.getId()){
				case R.id.svbottom_menu_back:  //返回
					if(!doBack()){
                        finish();
                    }
					break;
				case R.id.svbottom_menu_save: //保存
					saveData();
					break;
				case R.id.specialtask_item_name: //任务描述查看
				    showPopTextView(((SpecialTaskItem)arg0.getTag()).mTaskDes);
					break;
				case R.id.specialtask_item_text: //任务反馈输入
					if(!DataUtils.mUserData.isAdmin()){
						mPopEditText.showPopEditText(R.string.task_feedback, (TextView)arg0);
					}else{
						showPopTextView(((SpecialTaskItem)arg0.getTag()).mTaskFeedback);
					}
					break;
				case R.id.svbottom_menu_menu: //菜单
                	mPopMenu.showMenu();
                	break;
			}
		}
	}

	/**
	 * 保存数据
	 */
	private void saveData(){
		ContentValues values = new ContentValues();
		boolean hasNull = false;
		for(int i = 0; i < mBodyView.getChildCount(); i++){ //遍历所有数据项
			View view = mBodyView.getChildAt(i);
			TextView fd = (TextView)view.findViewById(R.id.specialtask_item_text);
			SpecialTaskItem item = (SpecialTaskItem)fd.getTag();
			values.clear();
			values.put(StoresManagerSettings.SpecialTaskColumns.TASK_FEEDBACK, fd.getText().toString()); //保存反馈数据
			if(Actions.isNull(fd.getText().toString())){
				hasNull = true;
			}
			values.put(StoresManagerSettings.SAVED, 0);
			if(item.mDbid == -1){
				values.put(StoresManagerSettings.SpecialTaskColumns.TASK_ID, item.mTaskID);
				values.put(StoresManagerSettings.SpecialTaskColumns.TASK_DES, item.mTaskDes);
				if(mVisitTaskInfo != null){
					values.put(StoresManagerSettings.SpecialTaskColumns.STOREID, mVisitTaskInfo.mStoreId);
				}
				Uri uri = getContentResolver().insert(StoresManagerSettings.SpecialTaskColumns.CONTENT_URI_NO_NOTIFICATION, values);
				item.mDbid = Long.parseLong(uri.getPathSegments().get(1));
			}else{
				getContentResolver().update(StoresManagerSettings.SpecialTaskColumns.getContentUri(item.mDbid, false),
						values, null, null);
			}
		}
		if(mVisitTaskInfo != null){
			if(hasNull){
				DatabaseUtil.saveVisitStatus(this, DatabaseUtil.TYPE_TASK , Integer.parseInt(mVisitTaskInfo.mVisitId), 0);
			}else{
				DatabaseUtil.saveVisitStatus(this, DatabaseUtil.TYPE_TASK , Integer.parseInt(mVisitTaskInfo.mVisitId), 1);
			}
		}
		Actions.toastShort(this, getString(R.string.datasave_success));
	}

	/**
     * 按键事件处理
     */
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            if(!doBack()){
                finish();
            }
            return true;
        }
        return false;
    }

    /**
     * 返回事件处理
     */
    private boolean doBack(){
        if(mPopTextView != null && mPopTextView.doBack()){
            return true;
        }
        if(mPopEditText != null && mPopEditText.doBack()){
            return true;
        }
        if(isDataChange){
        	if(DataUtils.mUserData.isAdmin()){
        		return false;
        	}
            popExitDialog();
            return true;
        }
        return false;
    }

    /**
     * 弹出任务描述弹窗
     * @param content 显示内容
     */
    private void showPopTextView(String content){
        mPopTextView.showPopTextView(R.string.task_description, content);
    }

    /**
	 * 更具查询结果更新任务数据
	 * @param cursor 查询结果数据
	 */
    private void updateTaskListFromCursor(Cursor cursor){
    	if(mSpecialTaskList != null){
			mSpecialTaskList.clear(); //清空数据
		}
    	try {
            final int nameIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.DataProjectsColumns.ITEM_NAME);
            final int saveIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.DataProjectsColumns.ITEM_SAVE);
            final int showIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.DataProjectsColumns.ITEM_SHOW);
            final int sequenceIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.DataProjectsColumns.ITEM_SEQUENCE);
            while (cursor.moveToNext()) {//遍历所有型号数据
            	SpecialTaskItem item = new SpecialTaskItem();
            	item.mTaskDes = cursor.getString(nameIndex);
            	item.isSave = cursor.getInt(saveIndex) == 1 ? true : false;
            	item.isShow = cursor.getInt(showIndex) == 1 ? true : false;
            	item.mTaskID = cursor.getInt(sequenceIndex);
            	if(item.isShow){
            		mSpecialTaskList.add(item);
            	}
            }
            //更新界面数据
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("updateDataItemFromCursor error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        		cursor = null;
        	}
        }
        if(mSpecialTaskList.size() > 0){ //没有特殊任务则跳过
        	startQueryTasksDataList();
        }
    }

    /**
     * 更具任务ID查找特殊任务项
     */
    private SpecialTaskItem getSpecialTaskItem(int taskId){
    	for(SpecialTaskItem item : mSpecialTaskList){
    		if(item.mTaskID == taskId){
    			return item;
    		}
    	}
    	return null;
    }

    /**
	 * 从管理员查询结果数据更新界面
	 */
	private void setDataFromAdminSearchData() {
		findViewById(R.id.svbottom_split_menu).setVisibility(View.GONE);
		findViewById(R.id.svbottom_menu_save).setVisibility(View.GONE);
		findViewById(R.id.svbottom_menu_menu).setVisibility(View.VISIBLE);
		findViewById(R.id.svbottom_menu_menu).setOnClickListener(this);
    	mPopMenu = new PopMenu(this, findViewById(R.id.bottom_menu), PopMenu.MENU_TASK);
        mPopMenu.setVisitTaskInfo(mVisitTaskInfo);
		if (DataUtils.mQueryVisitContentResult.Data != null && DataUtils.mQueryVisitContentResult.Data.Specials != null) {
			for(SyncModel.DataVisitContentSpecial content : DataUtils.mQueryVisitContentResult.Data.Specials){
				SpecialTaskItem item = new SpecialTaskItem();
				item.mTaskDes = content.Title;
				item.mTaskFeedback = content.Value;
				mSpecialTaskList.add(item);
			}
			updateBodyList();
		}
	}


	/**
     * 退出提示
     * 
     */
    private void popExitDialog() {
    	Actions.popExitDialog(this);
    }
}
